package com.qf.fmall2204.shopcart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2204.product.entity.Product;
import com.qf.fmall2204.product.entity.ProductImg;
import com.qf.fmall2204.product.entity.ProductSku;
import com.qf.fmall2204.product.mapper.ProductImgMapper;
import com.qf.fmall2204.product.mapper.ProductMapper;
import com.qf.fmall2204.product.mapper.ProductSkuMapper;
import com.qf.fmall2204.shopcart.entity.ShoppingCart;
import com.qf.fmall2204.shopcart.mapper.ShoppingCartMapper;
import com.qf.fmall2204.shopcart.service.IShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车  服务实现类
 * </p>
 *
 * @author dong
 * @since 2023-04-24
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ProductMapper productMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ProductImgMapper productImgMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ProductSkuMapper productSkuMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ShoppingCart cart) {

        //1. 判断是否需要合并购物车
        // SELECT * FROM shopping_cart WHERE user_id=20 AND product_id=3 AND sku_id=1;
        ShoppingCart dbcart = this.getOne(new QueryWrapper<ShoppingCart>()
                .eq("user_id", cart.getUserId())
                .eq("product_id", cart.getProductId())
                .eq("sku_id", cart.getSkuId()));

        if (dbcart!=null){
            // 合并购物车中的商品数量
            String dbNum = dbcart.getCartNum();
            int number = Integer.valueOf(cart.getCartNum()) + Integer.valueOf(dbNum);

            // 更新购物信息
            dbcart.setCartNum(number+""); // 更新购买量
            // 格式化日期 ： yyyy-MM-dd hh:mm:ss
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateStr = simpleDateFormat.format(new Date());
            dbcart.setCartTime(dateStr);  // 更新购物车日期
            // 更新
            this.updateById(dbcart);
        }else {
            // 新增购物车信息
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateStr = simpleDateFormat.format(new Date());
            cart.setCartTime(dateStr);

            // insert
            this.save(cart);
        }


    }

    @Override
    public List<ShoppingCart> listShopcart(Integer userId) {

        ShoppingCartMapper cartMapper = this.getBaseMapper();
        List<ShoppingCart> result = cartMapper.listShopcart(userId);

        return result;
    }

    @Override
    public List<ShoppingCart> listShopcartByMpAPI(Integer userId) {

        //1. SELECT * FROM shopping_cart WHERE user_id = 20;
        List<ShoppingCart> shoppingCarts = this.list(new QueryWrapper<ShoppingCart>().eq("user_id", userId));

        // List<ShoppingCart> ===> List<商品ID>
        List<String> productIdList = shoppingCarts.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        //2. SELECT product_name FROM product WHERE product_id IN (3);
        List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().in("product_id", productIdList));

        //3. SELECT url FROM product_img WHERE item_id IN (3);
        List<ProductImg> productImgs = productImgMapper
                .selectList(new QueryWrapper<ProductImg>().in("item_id", productIdList).eq("is_main", 1));

        //4. SELECT * FROM product_sku WHERE sku_id IN (1,2)
        // List<ShoppingCart> ===> List<商品SkuId>
        List<String> skuIdList = shoppingCarts.stream().map(ShoppingCart::getSkuId).collect(Collectors.toList());
        List<ProductSku> productSkus = productSkuMapper.selectList(new QueryWrapper<ProductSku>().in("sku_id", skuIdList));

        //5. 处理数据
        populateShoppingCart(shoppingCarts,productList,productImgs,productSkus);

        return shoppingCarts;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCartNumById(Integer cartId, Integer num) {

        ShoppingCart shoppingCart = this.getById(cartId);
        shoppingCart.setCartNum(num+"");

        this.updateById(shoppingCart);

    }

    @Override
    public List<ShoppingCart> listbycids(Integer[] cids) {

        ShoppingCartMapper shoppingCartMapper = this.getBaseMapper();

        List<ShoppingCart>  result = shoppingCartMapper.listbycids(cids);

        return result;
    }

    /**
     * 给传入的shoppingCarts填充缺失的数据
     *   "productName": "咪咪小虾条",
     *   "productImg": "mmxt_1.png",
     *   "skuName": "咪咪虾条 单包 50g",
     *   "originalPrice": 2,
     *   "sellPrice": 1,
     *   "stock": 254
     * @param shoppingCarts
     * @param productList
     * @param productImgs
     * @param productSkus
     *

     */
    private void populateShoppingCart(List<ShoppingCart> shoppingCarts, List<Product> productList,
                                      List<ProductImg> productImgs, List<ProductSku> productSkus) {

        // List<Product> ===>  Map<商品ID，商品对象>
        Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductId, product -> product));

        // List<ProductImg> ===> Map<商品ID，商品图片对象>
        Map<String, ProductImg> imgMap = productImgs.stream().collect(Collectors.toMap(ProductImg::getItemId, img -> img));

        // List<ProductSku> ====> Map<SkuID,ProductSku>
        Map<String, ProductSku> skuMap = productSkus.stream().collect(Collectors.toMap(ProductSku::getSkuId, sku -> sku));

        for (ShoppingCart shoppingCart : shoppingCarts) {

            // productName
            String productId = shoppingCart.getProductId();
            Product product = productMap.get(productId);
            shoppingCart.setProductName(product.getProductName());

            // productImg
            ProductImg productImg = imgMap.get(productId);
            shoppingCart.setProductImg(productImg.getUrl());

            // skuName: "咪咪虾条 单包 50g",
            // originalPrice: 2,
            // sellPrice: 1,
            // stock: 254

            String skuId = shoppingCart.getSkuId();
            ProductSku productSku = skuMap.get(skuId);
            shoppingCart.setSkuName(productSku.getSkuName());
            shoppingCart.setOriginalPrice(productSku.getOriginalPrice());
            shoppingCart.setSellPrice(productSku.getSellPrice());
            shoppingCart.setStock(productSku.getStock());

        }

    }
}
